<template>
  <el-container class="book-detail-container">
    <!-- 顶部导航 -->
    <el-header class="detail-header">
      <div class="header-content">
        <el-button @click="goBack" icon="ArrowLeft" text>返回</el-button>
        <el-divider direction="vertical" />
        <span class="page-title">图书详情</span>
      </div>
    </el-header>

    <!-- 主要内容区域 -->
    <el-main class="detail-main">
      <el-row :gutter="40">
        <!-- 左侧图书信息 -->
        <el-col :span="8">
          <el-card class="book-info-card" shadow="hover">
            <div class="book-cover-section">
              <img :src="bookDetail.cover" :alt="bookDetail.title" class="book-cover" />
              <div class="book-status">
                <el-tag :type="bookDetail.status === '可借' ? 'success' : 'danger'" size="large">
                  {{ bookDetail.status }}
                </el-tag>
              </div>
            </div>
            
            <div class="book-basic-info">
              <h2 class="book-title">{{ bookDetail.title }}</h2>
              <p class="book-author">作者：{{ bookDetail.author }}</p>
              <p class="book-publisher">出版社：{{ bookDetail.publisher }}</p>
              <p class="book-isbn">ISBN：{{ bookDetail.isbn }}</p>
              <p class="book-publish-date">出版日期：{{ bookDetail.publishDate }}</p>
              <p class="book-pages">页数：{{ bookDetail.pages }}页</p>
              <p class="book-language">语言：{{ bookDetail.language }}</p>
            </div>

            <div class="book-rating-section">
              <div class="rating-display">
                <el-rate 
                  v-model="bookDetail.rating" 
                  disabled 
                  show-score 
                  text-color="#ff9900"
                  score-template="{value}"
                />
                <span class="rating-count">({{ bookDetail.ratingCount }}人评价)</span>
              </div>
            </div>

            <div class="book-actions">
              <el-button 
                type="primary" 
                size="large" 
                @click="handleBorrow"
                :disabled="bookDetail.status !== '可借'"
                :loading="borrowLoading"
              >
                <el-icon><Reading /></el-icon>
                {{ bookDetail.status === '可借' ? '立即借阅' : '已借出' }}
              </el-button>
              
              <el-button 
                type="info" 
                size="large" 
                @click="addToFavorites"
                :loading="favoriteLoading"
              >
                <el-icon><Star /></el-icon>
                {{ isInFavorites ? '取消收藏' : '加入收藏' }}
              </el-button>
              
              <el-button 
                type="success" 
                size="large" 
                @click="startReading"
              >
                <el-icon><VideoPlay /></el-icon>
                开始阅读
              </el-button>
            </div>
          </el-card>
        </el-col>

        <!-- 右侧详细信息 -->
        <el-col :span="16">
          <!-- 图书详细信息 -->
          <el-card class="detail-card" shadow="hover">
            <template #header>
              <div class="card-header">
                <span>图书信息</span>
              </div>
            </template>
            
            <el-descriptions :column="2" border>
              <el-descriptions-item label="分类">{{ bookDetail.category }}</el-descriptions-item>
              <el-descriptions-item label="索书号">{{ bookDetail.callNumber }}</el-descriptions-item>
              <el-descriptions-item label="馆藏位置">{{ bookDetail.location }}</el-descriptions-item>
              <el-descriptions-item label="借阅次数">{{ bookDetail.borrowCount }}次</el-descriptions-item>
              <el-descriptions-item label="当前借阅人" v-if="bookDetail.status === '借出'">
                {{ bookDetail.currentBorrower }}
              </el-descriptions-item>
              <el-descriptions-item label="应还日期" v-if="bookDetail.status === '借出'">
                {{ bookDetail.returnDate }}
              </el-descriptions-item>
            </el-descriptions>

            <div class="book-description">
              <h4>内容简介</h4>
              <p>{{ bookDetail.description }}</p>
            </div>

            <div class="book-catalog" v-if="bookDetail.catalog">
              <h4>目录</h4>
              <el-collapse>
                <el-collapse-item 
                  v-for="(chapter, index) in bookDetail.catalog" 
                  :key="index"
                  :title="chapter.title"
                >
                  <div v-if="chapter.subChapters">
                    <div 
                      v-for="subChapter in chapter.subChapters" 
                      :key="subChapter.id"
                      class="sub-chapter"
                    >
                      {{ subChapter.title }}
                    </div>
                  </div>
                </el-collapse-item>
              </el-collapse>
            </div>
          </el-card>

          <!-- 借阅历史 -->
          <el-card class="history-card" shadow="hover">
            <template #header>
              <div class="card-header">
                <span>借阅历史</span>
                <el-button type="text" @click="viewAllHistory">查看全部</el-button>
              </div>
            </template>
            
            <el-table :data="borrowHistory" style="width: 100%">
              <el-table-column prop="borrower" label="借阅人" width="120" />
              <el-table-column prop="borrowDate" label="借阅日期" width="120" />
              <el-table-column prop="returnDate" label="归还日期" width="120" />
              <el-table-column prop="status" label="状态" width="80">
                <template #default="scope">
                  <el-tag :type="scope.row.status === '已归还' ? 'success' : 'warning'">
                    {{ scope.row.status }}
                  </el-tag>
                </template>
              </el-table-column>
            </el-table>
          </el-card>

          <!-- 读者评论 -->
          <el-card class="comments-card" shadow="hover">
            <template #header>
              <div class="card-header">
                <span>读者评论 ({{ comments.length }})</span>
                <el-button type="primary" @click="showCommentDialog = true">
                  <el-icon><ChatDotRound /></el-icon>
                  写评论
                </el-button>
              </div>
            </template>
            
            <div class="comments-section">
              <div v-if="comments.length === 0" class="no-comments">
                <el-empty description="暂无评论" />
              </div>
              
              <div v-else class="comments-list">
                <div 
                  v-for="comment in comments" 
                  :key="comment.id"
                  class="comment-item"
                >
                  <div class="comment-header">
                    <el-avatar :src="comment.userAvatar" size="small" />
                    <span class="comment-author">{{ comment.author }}</span>
                    <el-rate 
                      v-model="comment.rating" 
                      disabled 
                      size="small"
                    />
                    <span class="comment-time">{{ comment.time }}</span>
                  </div>
                  <div class="comment-content">
                    {{ comment.content }}
                  </div>
                  <div class="comment-actions">
                    <el-button type="text" size="small" @click="likeComment(comment.id)">
                      <el-icon><ThumbsUp /></el-icon>
                      点赞 ({{ comment.likes }})
                    </el-button>
                    <el-button type="text" size="small" @click="replyComment(comment.id)">
                      <el-icon><ChatDotRound /></el-icon>
                      回复
                    </el-button>
                  </div>
                </div>
              </div>
            </div>
          </el-card>

          <!-- 相关推荐 -->
          <el-card class="recommend-card" shadow="hover">
            <template #header>
              <div class="card-header">
                <span>相关推荐</span>
              </div>
            </template>
            
            <el-row :gutter="20">
              <el-col :span="8" v-for="book in relatedBooks" :key="book.id">
                <el-card 
                  class="related-book-card" 
                  shadow="hover"
                  @click="viewBook(book.id)"
                >
                  <img :src="book.cover" class="related-book-cover" />
                  <div class="related-book-info">
                    <h5>{{ book.title }}</h5>
                    <p>{{ book.author }}</p>
                    <el-rate v-model="book.rating" disabled size="small" />
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </el-card>
        </el-col>
      </el-row>
    </el-main>

    <!-- 写评论对话框 -->
    <el-dialog 
      v-model="showCommentDialog" 
      title="写评论" 
      width="500px"
    >
      <el-form :model="newComment" :rules="commentRules" ref="commentFormRef">
        <el-form-item label="评分" prop="rating">
          <el-rate v-model="newComment.rating" />
        </el-form-item>
        <el-form-item label="评论内容" prop="content">
          <el-input 
            v-model="newComment.content" 
            type="textarea" 
            :rows="4"
            placeholder="请分享您的阅读感受..."
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showCommentDialog = false">取消</el-button>
          <el-button type="primary" @click="submitComment" :loading="commentLoading">
            提交评论
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 借阅确认对话框 -->
    <el-dialog 
      v-model="borrowDialogVisible" 
      title="借阅确认" 
      width="400px"
    >
      <div class="borrow-info">
        <p><strong>图书：</strong>{{ bookDetail.title }}</p>
        <p><strong>作者：</strong>{{ bookDetail.author }}</p>
        <p><strong>借阅期限：</strong>30天</p>
        <p><strong>应还日期：</strong>{{ expectedReturnDate }}</p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="borrowDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmBorrow" :loading="borrowLoading">
            确认借阅
          </el-button>
        </span>
      </template>
    </el-dialog>
  </el-container>
</template>

<script>
import { 
  ArrowLeft, 
  Reading, 
  Star, 
  VideoPlay, 
  ChatDotRound, 
  ThumbsUp 
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'BookDetailPage',
  components: {
    ArrowLeft,
    Reading,
    Star,
    VideoPlay,
    ChatDotRound,
    ThumbsUp
  },
  data() {
    return {
      // 图书详情数据（这些数据将从后端API获取）
      bookDetail: {
        id: 1,
        title: '三体',
        author: '刘慈欣',
        publisher: '重庆出版社',
        isbn: '9787536692930',
        publishDate: '2008-01-01',
        pages: 302,
        language: '中文',
        cover: 'https://img3.doubanio.com/view/subject/l/public/s2768378.jpg',
        status: '可借', // 可借、借出、预约
        rating: 4.8,
        ratingCount: 1250,
        category: '科幻小说',
        callNumber: 'I247.55/1234',
        location: '三楼文学区 A区',
        borrowCount: 156,
        currentBorrower: '',
        returnDate: '',
        description: '地球文明向宇宙发出广播，寻找其他文明。四百年后，三体文明回应了地球的广播，但他们的回应充满了敌意。地球文明面临着前所未有的危机，人类必须团结起来，共同面对来自宇宙的威胁。',
        catalog: [
          {
            title: '第一部：地球往事',
            subChapters: [
              { id: 1, title: '第一章：科学边界' },
              { id: 2, title: '第二章：农场主' },
              { id: 3, title: '第三章：红岸基地' }
            ]
          },
          {
            title: '第二部：黑暗森林',
            subChapters: [
              { id: 4, title: '第一章：面壁者' },
              { id: 5, title: '第二章：破壁人' }
            ]
          }
        ]
      },

      // 借阅历史
      borrowHistory: [
        {
          borrower: '张三',
          borrowDate: '2024-01-01',
          returnDate: '2024-01-31',
          status: '已归还'
        },
        {
          borrower: '李四',
          borrowDate: '2024-02-01',
          returnDate: '2024-03-01',
          status: '已归还'
        },
        {
          borrower: '王五',
          borrowDate: '2024-03-15',
          returnDate: '2024-04-15',
          status: '借阅中'
        }
      ],

      // 评论数据
      comments: [
        {
          id: 1,
          author: '科幻爱好者',
          userAvatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
          rating: 5,
          content: '这是一部非常优秀的科幻小说，作者刘慈欣的想象力令人叹服。书中关于宇宙文明的思考深刻而震撼。',
          time: '2024-01-15 14:30',
          likes: 25
        },
        {
          id: 2,
          author: '文学评论家',
          userAvatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
          rating: 4,
          content: '虽然有些情节略显复杂，但整体来说是一部值得一读的好书。',
          time: '2024-01-10 09:15',
          likes: 12
        }
      ],

      // 相关推荐
      relatedBooks: [
        {
          id: 2,
          title: '球状闪电',
          author: '刘慈欣',
          cover: 'https://img2.doubanio.com/view/subject/l/public/s1070959.jpg',
          rating: 4.5
        },
        {
          id: 3,
          title: '流浪地球',
          author: '刘慈欣',
          cover: 'https://img1.doubanio.com/view/subject/l/public/s29651121.jpg',
          rating: 4.3
        },
        {
          id: 4,
          title: '超新星纪元',
          author: '刘慈欣',
          cover: 'https://img3.doubanio.com/view/subject/l/public/s29634528.jpg',
          rating: 4.2
        }
      ],

      // 状态控制
      borrowLoading: false,
      favoriteLoading: false,
      commentLoading: false,
      showCommentDialog: false,
      borrowDialogVisible: false,
      isInFavorites: false,

      // 新评论表单
      newComment: {
        rating: 5,
        content: ''
      },

      // 评论验证规则
      commentRules: {
        rating: [
          { required: true, message: '请选择评分', trigger: 'change' }
        ],
        content: [
          { required: true, message: '请输入评论内容', trigger: 'blur' },
          { min: 10, max: 500, message: '评论长度在 10 到 500 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    // 计算应还日期
    expectedReturnDate() {
      const date = new Date()
      date.setDate(date.getDate() + 30)
      return date.toLocaleDateString()
    }
  },
  methods: {
    // 返回上一页
    goBack() {
      this.$router.go(-1)
    },

    // 获取图书详情（从后端API）
    async fetchBookDetail(bookId) {
      try {
        // 这里应该调用后端API
        // const response = await this.$http.get(`/api/books/${bookId}`)
        // this.bookDetail = response.data
        
        // 模拟API调用
        console.log('获取图书详情:', bookId)
        
        // 检查是否已收藏
        this.checkFavoriteStatus(bookId)
      } catch (error) {
        ElMessage.error('获取图书信息失败')
      }
    },

    // 检查收藏状态
    async checkFavoriteStatus(bookId) {
      try {
        // 这里应该调用后端API检查收藏状态
        // const response = await this.$http.get(`/api/favorites/check/${bookId}`)
        // this.isInFavorites = response.data.isFavorite
        
        // 模拟检查
        this.isInFavorites = false
      } catch (error) {
        console.error('检查收藏状态失败:', error)
      }
    },

    // 借阅处理
    handleBorrow() {
      if (this.bookDetail.status !== '可借') {
        ElMessage.warning('该图书当前不可借阅')
        return
      }
      this.borrowDialogVisible = true
    },

    // 确认借阅
    async confirmBorrow() {
      this.borrowLoading = true
      try {
        // 这里应该调用后端API
        // await this.$http.post(`/api/books/${this.bookDetail.id}/borrow`)
        
        // 模拟API调用
        await new Promise(resolve => setTimeout(resolve, 1000))
        
        this.bookDetail.status = '借出'
        this.bookDetail.currentBorrower = '当前用户'
        this.bookDetail.returnDate = this.expectedReturnDate
        this.borrowDialogVisible = false
        
        ElMessage.success('借阅成功！请在30天内归还')
      } catch (error) {
        ElMessage.error('借阅失败，请重试')
      } finally {
        this.borrowLoading = false
      }
    },

    // 添加到收藏
    async addToFavorites() {
      this.favoriteLoading = true
      try {
        if (this.isInFavorites) {
          // 取消收藏
          // await this.$http.delete(`/api/favorites/${this.bookDetail.id}`)
          ElMessage.success('已取消收藏')
        } else {
          // 添加收藏
          // await this.$http.post(`/api/favorites/${this.bookDetail.id}`)
          ElMessage.success('已添加到收藏')
        }
        this.isInFavorites = !this.isInFavorites
      } catch (error) {
        ElMessage.error('操作失败，请重试')
      } finally {
        this.favoriteLoading = false
      }
    },

    // 开始阅读
    startReading() {
      this.$router.push({
        name: 'ReaderPage',
        params: { bookId: this.bookDetail.id }
      })
    },

    // 查看全部借阅历史
    viewAllHistory() {
      ElMessage.info('查看全部借阅历史')
      // 这里可以跳转到历史页面或显示更多历史记录
    },

    // 提交评论
    async submitComment() {
      try {
        await this.$refs.commentFormRef.validate()
        this.commentLoading = true
        
        // 这里应该调用后端API
        // await this.$http.post(`/api/books/${this.bookDetail.id}/comments`, this.newComment)
        
        // 模拟API调用
        await new Promise(resolve => setTimeout(resolve, 1000))
        
        // 添加新评论到列表
        const newComment = {
          id: Date.now(),
          author: '当前用户',
          userAvatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
          rating: this.newComment.rating,
          content: this.newComment.content,
          time: new Date().toLocaleString(),
          likes: 0
        }
        
        this.comments.unshift(newComment)
        this.showCommentDialog = false
        this.newComment = { rating: 5, content: '' }
        
        ElMessage.success('评论提交成功')
      } catch (error) {
        if (error !== 'validation failed') {
          ElMessage.error('评论提交失败')
        }
      } finally {
        this.commentLoading = false
      }
    },

    // 点赞评论
    likeComment(commentId) {
      const comment = this.comments.find(c => c.id === commentId)
      if (comment) {
        comment.likes++
        ElMessage.success('点赞成功')
      }
    },

    // 回复评论
    replyComment(commentId) {
      ElMessage.info('回复功能开发中')
    },

    // 查看相关图书
    viewBook(bookId) {
      this.$router.push({
        name: 'BookDetailPage',
        params: { bookId }
      })
    }
  },

  // 页面加载时获取数据
  mounted() {
    const bookId = this.$route.params.bookId || 1
    this.fetchBookDetail(bookId)
  },

  // 路由参数变化时重新获取数据
  watch: {
    '$route.params.bookId': {
      handler(newBookId) {
        if (newBookId) {
          this.fetchBookDetail(newBookId)
        }
      },
      immediate: true
    }
  }
}
</script>

<style scoped>
.book-detail-container {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.detail-header {
  background: white;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  align-items: center;
  padding: 0 20px;
  height: 60px;
}

.header-content {
  display: flex;
  align-items: center;
  gap: 10px;
}

.page-title {
  font-weight: 600;
  color: #303133;
}

.detail-main {
  padding: 20px;
}

.book-info-card {
  border-radius: 8px;
  overflow: hidden;
}

.book-cover-section {
  position: relative;
  text-align: center;
  margin-bottom: 20px;
}

.book-cover {
  width: 100%;
  max-width: 300px;
  height: 400px;
  object-fit: cover;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.book-status {
  position: absolute;
  top: 10px;
  right: 10px;
}

.book-basic-info {
  margin-bottom: 20px;
}

.book-title {
  margin: 0 0 15px 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.book-author,
.book-publisher,
.book-isbn,
.book-publish-date,
.book-pages,
.book-language {
  margin: 8px 0;
  color: #606266;
  font-size: 14px;
}

.book-rating-section {
  margin-bottom: 20px;
  text-align: center;
}

.rating-display {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
}

.rating-count {
  color: #909399;
  font-size: 12px;
}

.book-actions {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.detail-card,
.history-card,
.comments-card,
.recommend-card {
  margin-bottom: 20px;
  border-radius: 8px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.book-description,
.book-catalog {
  margin-top: 20px;
}

.book-description h4,
.book-catalog h4 {
  margin-bottom: 10px;
  color: #303133;
}

.book-description p {
  line-height: 1.6;
  color: #606266;
}

.sub-chapter {
  padding: 5px 0;
  color: #606266;
  font-size: 14px;
}

.comments-section {
  margin-top: 20px;
}

.comment-item {
  border-bottom: 1px solid #f0f0f0;
  padding: 15px 0;
}

.comment-item:last-child {
  border-bottom: none;
}

.comment-header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
}

.comment-author {
  font-weight: 600;
  color: #303133;
}

.comment-time {
  color: #909399;
  font-size: 12px;
  margin-left: auto;
}

.comment-content {
  line-height: 1.6;
  color: #606266;
  margin-bottom: 10px;
}

.comment-actions {
  display: flex;
  gap: 15px;
}

.borrow-info p {
  margin: 10px 0;
  line-height: 1.6;
}

.related-book-card {
  cursor: pointer;
  transition: all 0.3s;
  border-radius: 8px;
  overflow: hidden;
}

.related-book-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.related-book-cover {
  width: 100%;
  height: 150px;
  object-fit: cover;
}

.related-book-info {
  padding: 10px;
}

.related-book-info h5 {
  margin: 0 0 5px 0;
  font-size: 14px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.related-book-info p {
  margin: 0 0 5px 0;
  color: #909399;
  font-size: 12px;
}

.no-comments {
  text-align: center;
  padding: 40px 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .detail-main {
    padding: 10px;
  }
  
  .book-cover {
    max-width: 200px;
    height: 300px;
  }
  
  .book-actions {
    flex-direction: row;
    flex-wrap: wrap;
  }
  
  .book-actions .el-button {
    flex: 1;
    min-width: 120px;
  }
}
</style> 